using System;
using System.Collections.Generic;
using Cz;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Cz.CzJson
{
    public class CzJson2Dictionary : ICzJson
    {
        public void Start()
        {
            Console.WriteLine("CzJson2Dictionary Start");
        }

        public T Deserialize<T>(string json)
        {
            return (T)Deserialize(JsonConvert.DeserializeObject<JToken>(json));
        }

        public string Serialize(object value)
        {
            return JsonConvert.SerializeObject(value);
        }
        
        object Deserialize(JToken jToken)
        {
            switch (jToken)
            {
                case null:
                    return null;
                case JObject jObject:
                    var ret = new Dictionary<string, object>();
                    foreach (var (key, value) in jObject)
                    {
                        ret[key] = Deserialize(value);
                    }
                    return ret;
                case JArray jArray:
                    var array = new object[jArray.Count];
                    for (int i = 0; i < jArray.Count; i++)
                    {
                        array[i] = Deserialize(jArray[i]);
                    }
                    return array;
                case JValue jValue:
                    return jValue.Value;
                default:
                    throw new Exception("未知的类型:" + jToken.ToJson());
            }
        }
    }
}